package org.jeecgframework.web.controller;

import com.fr.base.StringUtils;
import com.mybatis.ext.WiseCoreService;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.collections.*;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.hibernate.qbc.HqlQuery;
import org.jeecgframework.core.common.hibernate.qbc.PageList;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.*;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.service.CbsInspectionAppointmentServiceI;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.service.ZyPlanRecordServiceI;
import org.jeecgframework.web.service.ZyWorkFlowService;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.system.service.UserService;
import org.jeecgframework.web.util.SectionEnum;
import org.jeecgframework.web.util.SendMessage;
import org.jeecgframework.web.util.StaticValue;
import org.jeecgframework.workflow.service.ActivitiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.CollationKey;
import java.text.Collator;
import java.util.*;


/**
 * @author onlineGenerator
 * @version V1.0
 * @Title: Controller
 * @Description: 巡检预约
 * @date 2016-08-22 14:35:02
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsInspectionAppointmentController")
public class CbsInspectionAppointmentController extends BaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(CbsInspectionAppointmentController.class);

    @Autowired
    private ZyCommonService zyCommonService;

    @Autowired
    private CbsInspectionAppointmentServiceI cbsInspectionAppointmentService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private ZyWorkFlowService zyWorkFlowService;
    @Autowired
    private ActivitiService activitiService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private ZyPlanRecordServiceI zyPlanRecordService;

    @Autowired
    private WiseCoreService wiseCoreService;

    @Autowired
    private UserService userService;

    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    /**
     * 巡检预约列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "cbsInspectionAppointment")
    public ModelAndView cbsInspectionAppointment(HttpServletRequest request) {
        return new ModelAndView("com/zybk/cbsinspectionappointment/cbsInspectionAppointmentList");
    }

    @RequestMapping(params = "getInspectionAppointmentApprovalList")
    public void getInspectionAppointmentApprovalList(VappointTask vappointTask, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        Map param = new HashMap<>();
        param.put("assignee",ResourceUtil.getSessionUserName().getUserName());
        if(userService.hasRole(ResourceUtil.getSessionUserName().getUserName(),StaticValue.CBS_HD_ROLE_CODE)){
            param.put("wechat","1");
        }
        for (Object key : request.getParameterMap().keySet()) {
            if ((String[]) request.getParameterMap().get(key) != null) {
                for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                    if (((String[]) request.getParameterMap().get(key))[i] != null) {
                        param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
                    }
                }
            }
        }
        if(!StringUtil.isEmpty(oConvertUtils.getString(param.get("createDate_begin")))){
            param.put("createDate_begin",oConvertUtils.getString(param.get("createDate_begin"))+" 01:00:00");
        }
        if(!StringUtil.isEmpty(oConvertUtils.getString(param.get("createDate_end")))){
            param.put("createDate_end",oConvertUtils.getString(param.get("createDate_end"))+" 23:59:59");
        }
        wiseCoreService.selectDataGrid("selectAppointTask",param,dataGrid);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(CbsInspectionAppointmentEntity cbsInspectionAppointment, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(CbsInspectionAppointmentEntity.class, dataGrid);
        //查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsInspectionAppointment, request.getParameterMap());
        try {
            //自定义追加查询条件
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        cq.add();
        this.cbsInspectionAppointmentService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }

    /***
     * 跳转到审批页面
     * @param request
     * @param busId 业务id
     * @param instId 流程id
     * @param taskId 节点Id
     * @return
     */
    @RequestMapping(params = "goApproval")
    public ModelAndView goApproval(HttpServletRequest request, String busId, String instId, String taskId, String idDtail) {
        CbsInspectionAppointmentEntity inspectionAppointment = systemService.get(CbsInspectionAppointmentEntity.class, busId);
        request.setAttribute("bus", inspectionAppointment);
        Task task = activitiService.getTask(taskId);
        request.setAttribute("task", task);
        request.setAttribute("inAppId",inspectionAppointment.getInAppId());
        request.setAttribute("instId", instId);
        request.setAttribute("idDtail", idDtail);
        List<ZyPlanRecordEntity> recordList = systemService.findHql("from ZyPlanRecordEntity where busId = ? order by createDate desc", busId);
        request.setAttribute("recordList", recordList);
        request.setAttribute("hasHd",userService.hasRole(ResourceUtil.getSessionUserName().getUserName(),StaticValue.CBS_HD_ROLE_CODE));
        request.setAttribute("hasCsa",userService.hasRole(ResourceUtil.getSessionUserName().getUserName(),StaticValue.RULE_CODE_BARCO_CSA));
        return new ModelAndView("com/zybk/cbsinspectionappointment/cbsInspectionAppointment-approval");
    }

    @RequestMapping(params = "existsAppoint")
    @ResponseBody
    public AjaxJson checkSnIfExistsAppoint(String snNum){
        AjaxJson result = new AjaxJson();
        result.setMsg(cbsInspectionAppointmentService.checkSnIfInAppoint(snNum));
        return result;
    }

    /**
     * 审批提交
     *
     * @param request
     * @param busId   业务id
     * @param instId  流程id
     * @param taskId  节点Id
     * @return
     */
    @RequestMapping(params = "doApprovalSubmit")
    @ResponseBody
    public AjaxJson doApprovalSubmit(HttpServletRequest request, String busId, String instId, String taskId, String status, String content) {
        AjaxJson j = new AjaxJson();
        message = "提交巡检预约成功";
        try {
            TSUser user = ResourceUtil.getSessionUserName();
            if (StringUtil.isNotEmpty(taskId)) {
                Task task = activitiService.getTask(taskId);
                if ("n".equals(zyWorkFlowService.checkTaskHandle(taskId))) {
                    message = "操作失败,该任务已被办理";
                } else if (StringUtil.isNotEmpty(task.getAssignee()) && !user.getUserName().equals(task.getAssignee())) {
                    message = "操作失败,该任务已转派给" + task.getAssignee();
                } else {
                    taskService.claim(taskId, user.getUserName());
                    zyWorkFlowService.processComplete("1", instId, "", "", "");
                    CbsInspectionAppointmentEntity inspectionAppointment = systemService.get(CbsInspectionAppointmentEntity.class, busId);
                    if(StringUtils.isEmpty(status)){
                        inspectionAppointment.setStatus("1");
                        systemService.saveOrUpdate(inspectionAppointment);
                    }else{
                        message = "0".equals(status) ? "巡检预约审批 - 同意" : "巡检预约审批 - 不同意";
                        inspectionAppointment.setStatus("2");
                        systemService.saveOrUpdate(inspectionAppointment);
                        //不同意  // 需要发送短信
                        if ("1".equals(status)) {
                            Map<String, Object> rejectMap = new HashMap<String, Object>();
                            rejectMap.put("content", content);
                            String sns = "";
                            for (CbsInspectionAppointmentEsEntity appEs : inspectionAppointment.getEsList()) {
                                sns += appEs.getEs().getSn() + ",";
                            }
                            if (StringUtil.isNotEmpty(sns)) {
                                sns = sns.substring(0, sns.length() - 1);
                            }
                            rejectMap.put("esSnNo", sns);
                            //发送给申请人 --  申请人的联系人信息
                            List<ZyContactsEntity> contactList = systemService.findHql("from ZyContactsEntity where tsBaseUser.userName = ?", inspectionAppointment.getCreateBy());
                            if (contactList.size() > 0) {
                                if (StringUtil.isNotEmpty(contactList.get(0).getCellphone1())) {
                                    SendMessage.sendSMSFTL(contactList.get(0).getCellphone1(), "sms_inspectionAppointmentReturn.ftl", rejectMap, systemService);
                                } else if (StringUtil.isNotEmpty(contactList.get(0).getCellphone2())) {
                                    SendMessage.sendSMSFTL(contactList.get(0).getCellphone2(), "sms_inspectionAppointmentReturn.ftl", rejectMap, systemService);
                                }
                            }
                        }
                    }
                    zyPlanRecordService.savePlanRecord(busId, instId, taskId, "", user.getUserName(), StringUtil.isNotEmpty(content) ? content : message);
                }
            }
            systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            message = "巡检预约提交失败";
            e.printStackTrace();
        }
        j.setMsg(message);
        return j;
    }


    /**
     * 取消流程
     * instId 流程实例id
     */
    @RequestMapping(params = "closeFlow")
    @ResponseBody
    public AjaxJson closeFlow(String instId, String taskId, String busId, String content) {
        AjaxJson j = new AjaxJson();
        message = "取消成功";
        String type = "";
        try {
            CbsProcurementNoteEntity note = systemService.findUniqueByProperty(CbsProcurementNoteEntity.class, "id", busId);
            //是采购单流程
            if (StringUtil.isNotEmpty(note)) {
                //设置采购单状态为已取消
                note.setState("3");
                systemService.saveOrUpdate(note);
                type = "采购单";
            } else {
                CbsInspectionAppointmentEntity appointmentEntity = systemService.get(CbsInspectionAppointmentEntity.class,busId);
                if(StringUtil.isNotEmpty(appointmentEntity)){
//                    设置采购单状态为已取消
                    appointmentEntity.setStatus("3");
                    systemService.saveOrUpdate(appointmentEntity);
                }
                type = "巡检预约";
            }
            if ("n".equals(zyWorkFlowService.checkTaskHandle(taskId))) {
                message = "取消失败,该任务已被办理";
            } else {
                TSUser user = ResourceUtil.getSessionUserName();
                taskService.claim(taskId, user.getUserName());
                runtimeService.deleteProcessInstance(instId, user.getRealName() + "取消流程");
                zyPlanRecordService.savePlanRecord(busId, instId, taskId, "", user.getUserName(), content);
            }
            systemService.addLog(type + message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "取消失败";
        }
        j.setMsg(type + message);
        return j;
    }

    /**
     * 巡检预约新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(HttpServletRequest req, String busId) {
        if (StringUtil.isNotEmpty(busId)) {
            CbsInspectionAppointmentEntity cbsInspectionAppointment = cbsInspectionAppointmentService.getEntity(CbsInspectionAppointmentEntity.class, busId);
            req.setAttribute("bus", cbsInspectionAppointment);
            if(cbsInspectionAppointment.getExpectDate() != null){
                req.setAttribute("expectDate",DateUtils.formatDate(cbsInspectionAppointment.getExpectDate(),"yyyy"));
            }
            req.setAttribute("expectSection",cbsInspectionAppointment.getExpectSection());
        }else{
            req.setAttribute("expectSection",0);
        }
        req.setAttribute("years",cbsInspectionAppointmentService.generateExpectYearsSelect());
        return new ModelAndView("com/zybk/cbsinspectionappointment/cbsInspectionAppointment-add");
    }


    /**
     * 添加巡检预约
     *
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(CbsInspectionAppointmentEntity cbsInspectionAppointment, HttpServletRequest request, String equipmentIdStr, String equipmentTypeStr) {
        AjaxJson j = new AjaxJson();
        message = "创建巡检预约成功";
        try {
            AjaxJson re = checkSection(cbsInspectionAppointment.getExpectDate(),cbsInspectionAppointment.getExpectSection());
            if(!re.isSuccess()){
                return re;
            }
            if (StringUtil.isNotEmpty(cbsInspectionAppointment.getId())) {
                CbsInspectionAppointmentEntity t = systemService.get(CbsInspectionAppointmentEntity.class, cbsInspectionAppointment.getId());
                MyBeanUtils.copyBeanNotNull2Bean(cbsInspectionAppointment, t);
                systemService.saveOrUpdate(t);
                systemService.deleteAllEntitie(t.getEsList());
            } else {
                cbsInspectionAppointment.setInAppId(cbsInspectionAppointmentService.genInAppId(cbsInspectionAppointment));
                cbsInspectionAppointment.setSource("1");
                cbsInspectionAppointmentService.save(cbsInspectionAppointment);
            }

            String equipmentIds[] = equipmentIdStr.split(",");
            String equipmentTypes[] = equipmentTypeStr.split(",");
            List<CbsInspectionAppointmentEsEntity> esList = new ArrayList<CbsInspectionAppointmentEsEntity>();
            for (int i = 0; i < equipmentIds.length; i++) {
                CbsInspectionAppointmentEsEntity es = new CbsInspectionAppointmentEsEntity();
                es.setEs(systemService.get(ZyEquipmentSpareEntity.class, equipmentIds[i]));
                es.setInspectionAppointment(cbsInspectionAppointment);
                es.setType(equipmentTypes[i]);
                esList.add(es);
            }
            systemService.batchSave(esList);
            // 0.草稿 1.提交 3.取消，4处理中
            if ("4".equals(cbsInspectionAppointment.getStatus())) {
//				cbsInspectionAppointment
                ProcessInstance inst = zyWorkFlowService.startOnlineProcess("cbs_inspection_appointment", cbsInspectionAppointment.getId(), new HashMap<String, Object>());
                zyWorkFlowService.goProcessNode(cbsInspectionAppointment.getId(), StaticValue.CBS_INSPECTION_APPOINTMENT_FLOW_KEY, "taskNode0", "taskNode1");
                Task task = taskService.createTaskQuery().processInstanceId(inst.getProcessInstanceId()).active().singleResult();
                TSUser user = ResourceUtil.getSessionUserName();
                zyPlanRecordService.savePlanRecord(cbsInspectionAppointment.getId(), inst.getProcessInstanceId(), task.getId(), "", user.getUserName(), message);
            }
            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "巡检预约添加失败";
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 巡检预约编辑页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(CbsInspectionAppointmentEntity cbsInspectionAppointment, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(cbsInspectionAppointment.getId())) {
            cbsInspectionAppointment = cbsInspectionAppointmentService.getEntity(CbsInspectionAppointmentEntity.class, cbsInspectionAppointment.getId());
            req.setAttribute("cbsInspectionAppointmentPage", cbsInspectionAppointment);
        }
        return new ModelAndView("com/zybk/cbsinspectionappointment/cbsInspectionAppointment-update");
    }

    /**
     * 更新巡检预约
     *
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(CbsInspectionAppointmentEntity cbsInspectionAppointment, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "巡检预约更新成功";
        CbsInspectionAppointmentEntity t = cbsInspectionAppointmentService.get(CbsInspectionAppointmentEntity.class, cbsInspectionAppointment.getId());
        try {

            MyBeanUtils.copyBeanNotNull2Bean(cbsInspectionAppointment, t);
            cbsInspectionAppointmentService.saveOrUpdate(t);
            systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "巡检预约更新失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }


    /**
     * 删除巡检预约
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(CbsInspectionAppointmentEntity cbsInspectionAppointment, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        cbsInspectionAppointment = systemService.getEntity(CbsInspectionAppointmentEntity.class, cbsInspectionAppointment.getId());
        message = "巡检预约删除成功";
        try {
            cbsInspectionAppointmentService.delete(cbsInspectionAppointment);
            systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "巡检预约删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除巡检预约
     *
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "巡检预约删除成功";
        try {
            for (String id : ids.split(",")) {
                CbsInspectionAppointmentEntity cbsInspectionAppointment = systemService.getEntity(CbsInspectionAppointmentEntity.class,
                        id
                );
                cbsInspectionAppointmentService.delete(cbsInspectionAppointment);
                systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            message = "巡检预约删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    @RequestMapping(params = "checkSection")
    @ResponseBody
    public AjaxJson checkSection(Date expectDate,int section){
        AjaxJson result = new AjaxJson();
        Calendar c1 = Calendar.getInstance();
        Calendar selectDate = Calendar.getInstance();
        selectDate.setTime(expectDate);

        int m = c1.get(Calendar.MONTH)+1;
        int currentSection = m/3 ;
        if(m%3 > 0){
            currentSection++;
        }
        if(currentSection == 4 || currentSection == 3){
            if(section != 1){
                result.setSuccess(false);
                result.setMsg("当前只能选择第一季度");
            }
        }else{
            if(selectDate.get(Calendar.YEAR) == c1.get(Calendar.YEAR)){
                if(section - currentSection <= 1){
                    result.setSuccess(false);
                    result.setMsg("只能选择当前时间下个季度之后的任一季度");
                }
            }
        }
        return result;
    }

    @RequestMapping(params = "getExpectionByType")
    @ResponseBody
    public List<Map<String,Object>> getExpectionByType(String type, int value){

        List<SectionEnum> sectionEna = cbsInspectionAppointmentService.generateExpectSectionSelect(value);
        List<Map<String,Object>> sectionMap = new ArrayList<Map<String,Object>>();
        for(SectionEnum section : sectionEna){
            Map<String,Object> sMap = new HashMap<String,Object>();
            sMap.put("index",section.index);
            sMap.put("name",section.msg);
            sectionMap.add(sMap);
        }
        return sectionMap;
    }


}
